//
//  TTWebViewController.m
//  Tint
//
//  Created by Kevin Wu on 2/28/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "TTWebViewController.h"

@interface TTWebViewController (Private)

- (void)setUpToolbar;
- (void)setUpWebView;

- (void)releaseAllSubviews;

- (void)backItemClicked:(id)sender;
- (void)forwardItemClicked:(id)sender;
- (void)refreshItemClicked:(id)sender;
- (void)stopItemClicked:(id)sender;
- (void)actionItemClicked:(id)sender;

- (void)updateToolbarWithOrientation:(UIInterfaceOrientation)interfaceOrientation;

@end



@implementation TTWebViewController


#pragma mark - Memory

- (id)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (id)initWithURL:(NSURL *)URL {
    self = [self init];
    if (self) {
        _loadingURL = [[URL absoluteURL] copy];
    }
    return self;
}

- (void)dealloc {
    
    [self releaseAllSubviews];
    
    TTRelease(_actionSheetURL);
    TTRelease(_loadingURL);
    
    [super dealloc];
}



#pragma mark - UIViewController

- (void)loadView {
    [super loadView];
    
    [self setUpToolbar];
    [self setUpWebView];
    
    
    // For navigation bar
    UIActivityIndicatorView *aiv = [UIActivityIndicatorView activityIndicatorViewWithStyle:UIActivityIndicatorViewStyleWhite];
    [aiv startAnimating];
    _activityBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aiv];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self openURL:_loadingURL];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    
    [self releaseAllSubviews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self updateToolbarWithOrientation:self.interfaceOrientation];
}

- (void)viewWillDisappear:(BOOL)animated {
    // If the browser launched the media player, it steals the key window and never gives it
    // back, so this is a way to try and fix that.
    [self.view.window makeKeyWindow];
    
    [super viewWillDisappear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return TTIsSupportedOrientation(interfaceOrientation);
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self updateToolbarWithOrientation:toInterfaceOrientation];
}



#pragma mark - Public

- (NSURL *)URL {
    return _loadingURL ? _loadingURL : _webView.request.mainDocumentURL;
}

- (void)openURL:(NSURL *)URL {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [self openRequest:request];
}

- (void)openRequest:(NSURLRequest *)request {
    // The view must be loaded before you call this method.
    [_webView loadRequest:request];
}

- (BOOL)shouldPresentActionSheet:(UIActionSheet *)actionSheet {
    if (_actionSheet == actionSheet) {
        [_actionSheet addButtonWithTitle:TTLocalizedString(@"Open in Safari", @"[WebViewController] Action menu item title")];
        [_actionSheet addButtonWithTitle:TTLocalizedString(@"Copy URL", @"[WebViewController] Action menu item title")];
    }
    return YES;
}

- (void)clickedActionSheetButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [[UIApplication sharedApplication] openURL:_actionSheetURL];
    } else if (buttonIndex == 1) {
        [[UIPasteboard generalPasteboard] setURL:_actionSheetURL];
    }
}


#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet == _actionSheet) {
        [self clickedActionSheetButtonAtIndex:buttonIndex];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (actionSheet == _actionSheet) {
        _actionSheet.delegate = nil;
        TTRelease(_actionSheet);
        TTRelease(_actionSheetURL);
    }
}



#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    TTRelease(_loadingURL);
    _loadingURL = [request.mainDocumentURL copy];
    _backBarButtonItem.enabled = [_webView canGoBack];
    _forwardBatButtonItem.enabled = [_webView canGoForward];
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    self.title = TTLocalizedString(@"Loading...", @"[WebViewController] Main title while loading");
    if (!self.navigationItem.rightBarButtonItem) {
        [self.navigationItem setRightBarButtonItem:_activityBarButtonItem animated:YES];
    }
    
    _backBarButtonItem.enabled = [_webView canGoBack];
    _forwardBatButtonItem.enabled = [_webView canGoForward];
    
    for (int i=0; i<[_toolbar.items count]; ++i) {
        UIBarButtonItem *item = [_toolbar.items objectAtIndex:i];
        if (item.tag == 3) {
            NSMutableArray *newItems = [NSMutableArray arrayWithArray:_toolbar.items];
            [newItems replaceObjectAtIndex:i withObject:_stopBarButtonItem];
            _toolbar.items = newItems;
            break;
        }
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    TTRelease(_loadingURL);
    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (self.navigationItem.rightBarButtonItem == _activityBarButtonItem) {
        [self.navigationItem setRightBarButtonItem:nil animated:YES];
    }
    
    _backBarButtonItem.enabled = [_webView canGoBack];
    _forwardBatButtonItem.enabled = [_webView canGoForward];
    
    for (int i=0; i<[_toolbar.items count]; ++i) {
        UIBarButtonItem *item = [_toolbar.items objectAtIndex:i];
        if (item.tag == 3) {
            NSMutableArray *newItems = [NSMutableArray arrayWithArray:_toolbar.items];
            [newItems replaceObjectAtIndex:i withObject:_refreshBarButtonItem];
            _toolbar.items = newItems;
            break;
        }
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    
    TTRelease(_loadingURL);
    [self webViewDidFinishLoad:webView];
}

@end




@implementation TTWebViewController (Private)

- (void)setUpToolbar {
    
    _backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:TTTintBundleImage(@"Images/WebViewController/backIcon.png") 
                                                          style:UIBarButtonItemStylePlain 
                                                         target:self 
                                                         action:@selector(backItemClicked:)];
    _backBarButtonItem.tag = 2;
    _backBarButtonItem.enabled = NO;
    
    
    
    _forwardBatButtonItem = [[UIBarButtonItem alloc] initWithImage:TTTintBundleImage(@"Images/WebViewController/forwardIcon.png") 
                                                             style:UIBarButtonItemStylePlain 
                                                            target:self 
                                                            action:@selector(forwardItemClicked:)];
    _forwardBatButtonItem.tag = 1;
    _forwardBatButtonItem.enabled = NO;
    
    
    
    _refreshBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
                                                                          target:self 
                                                                          action:@selector(refreshItemClicked:)];
    _refreshBarButtonItem.tag = 3;
    
    
    
    _stopBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop 
                                                                       target:self 
                                                                       action:@selector(stopItemClicked:)];
    _stopBarButtonItem.tag = 3;
    
    
    
    _actionBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction 
                                                                         target:self 
                                                                         action:@selector(actionItemClicked:)];
    
    
    
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
                                                                                   target:nil 
                                                                                   action:NULL];
    
    
    
    // Create toolbar
    CGFloat toolbarHeight = TTToolbarHeightForOrientation(TTInterfaceOrientation());
    _toolbar = [[UIToolbar alloc] init];
    _toolbar.frame = TTRectMake(0.0, self.view.height-toolbarHeight, self.view.width, toolbarHeight);
    _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    
    _toolbar.items = [NSArray arrayWithObjects:
                      _backBarButtonItem, flexibleSpace,
                      _forwardBatButtonItem, flexibleSpace,
                      _refreshBarButtonItem, flexibleSpace,
                      _actionBarButtonItem, nil];
    TTRelease(flexibleSpace);
    
    [self.view addSubview:_toolbar];
}

- (void)setUpWebView {
    _webView = [[UIWebView alloc] init];
    _webView.frame = TTRectContract(self.view.bounds, 0.0, _toolbar.height);
    _webView.delegate = self;
    _webView.autoresizingMask = TTViewAutoresizingKeepMargin;
    _webView.scalesPageToFit = YES;
    [self.view addSubview:_webView];
}


- (void)releaseAllSubviews {
    _webView.delegate = nil;
    _actionSheet.delegate = nil;
    
    TTRelease(_webView);
    TTRelease(_toolbar);
    TTRelease(_actionSheet);
    
    TTRelease(_backBarButtonItem);
    TTRelease(_forwardBatButtonItem);
    TTRelease(_refreshBarButtonItem);
    TTRelease(_stopBarButtonItem);
    TTRelease(_actionBarButtonItem);
    
    TTRelease(_activityBarButtonItem);
}


- (void)backItemClicked:(id)sender {
    [_webView goBack];
}

- (void)forwardItemClicked:(id)sender {
    [_webView goForward];
}

- (void)refreshItemClicked:(id)sender {
    [_webView reload];
}

- (void)stopItemClicked:(id)sender {
    [_webView stopLoading];
}

- (void)actionItemClicked:(id)sender {
    // Dismiss the action menu if the user taps the action button again on the iPad.
    if ([_actionSheet isVisible]) {
        // It shouldn't be possible to tap the share action button again on anything but the iPad.
        TTDASSERT(TTIsPad());
        
        [_actionSheet dismissWithClickedButtonIndex:[_actionSheet cancelButtonIndex] animated:YES];
        
        // We remove the action sheet here just in case the delegate isn't properly implemented.
        _actionSheet.delegate = nil;
        TTRelease(_actionSheet);
        TTRelease(_actionSheetURL);
        
        // Don't show the menu again.
        return;
    }
    
    // Remember the URL at this point
    TTRelease(_actionSheetURL);
    _actionSheetURL = [self.URL copy];
    
    if (nil == _actionSheet) {
        _actionSheet = [[UIActionSheet alloc] initWithTitle:[_actionSheetURL absoluteString] 
                                                   delegate:self 
                                          cancelButtonTitle:nil 
                                     destructiveButtonTitle:nil 
                                          otherButtonTitles:nil];
        
        // Let -shouldPresentActionSheet: setup the action sheet
        if (![self shouldPresentActionSheet:_actionSheet]) {
            // A subclass decided to handle the action in another way
            TTRelease(_actionSheet);
            TTRelease(_actionSheetURL);
            return;
        }
        // Add "Cancel" button except for iPads
        if (!TTIsPad()) {
            NSInteger buttonIndex = [_actionSheet addButtonWithTitle:TTLocalizedString(@"Cancel", @"[WebViewController] Action menu item title")];
            [_actionSheet setCancelButtonIndex:buttonIndex];
        }
    }
    
    if (TTIsPad()) {
        [_actionSheet showFromBarButtonItem:_actionBarButtonItem animated:YES];
    } else {
        [_actionSheet showInView:self.view];
    }
}

- (void)updateToolbarWithOrientation:(UIInterfaceOrientation)interfaceOrientation {
    CGFloat toolbarHeight = TTToolbarHeightForOrientation(interfaceOrientation);
    _toolbar.frame = TTRectMake(0.0, self.view.height-toolbarHeight, self.view.width, toolbarHeight);
    _webView.frame = TTRectWithWH(self.view.width, self.view.height-toolbarHeight);
}

@end

